package com.pig4cloud.pigx.common.security.service;

import com.pig4cloud.pigx.admin.api.dto.UserInfo;
import com.pig4cloud.pigx.common.core.constant.CacheConstants;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.constant.enums.UserTypeEnum;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.shop.user.api.entity.ShopUser;
import com.pig4cloud.pigx.shop.user.api.feign.RemoteShopUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Slf4j
@RequiredArgsConstructor
public class PigxShopUserDetailServiceImpl implements PigxUserDetailsService {

	private final RemoteShopUserService remoteShopUserService;

	private final CacheManager cacheManager;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 读取缓存用户信息
		// Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS_MINI);
		// if (cache != null && cache.get(username) != null) {
		// return cache.get(username, PigxUser.class);
		// }
		// 获取用户信息
		ShopUser shopUserInfo = remoteShopUserService.getShopUserInfo(username, SecurityConstants.FROM_IN).getData();
		UserDetails userDetails = new PigxUser(shopUserInfo.getId(), shopUserInfo.getLoginAccount(), 1L,
				shopUserInfo.getPhone(), shopUserInfo.getHeaderUrl(), shopUserInfo.getNickName(),
				shopUserInfo.getRealName(), "", 1L, "", true, true, UserTypeEnum.TOC.getStatus(), true, true,
				AuthorityUtils.NO_AUTHORITIES);
		// if (cache != null) {
		// cache.put(username, userDetails);
		// }
		return userDetails;
	}

	@Override
	public UserDetails loadUserByUser(PigxUser pigxUser) {
		return this.loadUserByUsername(pigxUser.getUsername());
	}

	@Override
	public boolean support(String clientId, String grantType) {
		return "shop_user".equals(clientId);
	}

	@Override
	public int getOrder() {
		return Integer.MIN_VALUE + 1;
	}

}
